from ..database import database, TABLE_PREFIX
from flask._compat import with_metaclass, string_types
from peewee import *
import datetime
from .country import Country
from .currency import Currency
from .account import Account
import shortuuid


class Member(database.Model):
    id = PrimaryKeyField(db_column='id')
    credit_rating = IntegerField(db_column='credit_rating', default=0, help_text='信誉等级')
    screen_name = CharField(db_column='screen_name', max_length=40, help_text='显示名称')
    head_image = CharField(db_column='head_image', max_length=400, help_text='头像地址')
    sales_rate = DecimalField(db_column='sale_rate', default=0.00, decimal_places=1, help_text='卖家好评率')
    buyer_rate = DecimalField(db_column='buyer_rate', default=0, decimal_places=1, help_text='买家好评率')
    deal_count = IntegerField(db_column='deal_count', default=0, help_text='已成交数')
    created_at = DateTimeField(db_column='created_at', default=datetime.datetime.now, help_text='创建时间')
    updated_at = DateTimeField(db_column='updated_at', help_text='最后更新时间')
    country = ForeignKeyField(Country)
    currency = ForeignKeyField(Currency)
    account = ForeignKeyField(Account)
    secret_key = CharField(db_column='secret_key', default=shortuuid.uuid, max_length=64, help_text='会员安全key')
    first_name = CharField(db_column='first_name', help_text='姓', null=True)
    last_name = CharField(db_column='last_name', help_text='名', null=True)
    grade = CharField(db_column='grade', help_text='姓别', default='male')
    phone = CharField(db_column='phone', help_text='手机号码', null=True)
    email = CharField(db_column='email', help_text='邮箱地址', null=True)
    status = CharField(db_column='status', help_text='状态', default='normal', max_length=20)

    # class Meta:
    #     db_table = '{}_{}'.format(TABLE_PREFIX, 'members')

    @classmethod
    def get_member(cls, member_id):
        return cls.get_or_none((cls.id == member_id) & (cls.status == 'normal'))

# @Member.pre_save
# def member_pre_save_handler(instance, created):
#     if created and instance.id is None:
#         from .table_seq import TableSeq
#         meta = getattr(instance, '_meta')
#         if meta:
#             code = getattr(meta, 'db_table') or 'member'
#             instance.id = TableSeq.get_seq(code)
